<template>
  <div class="card pdca">
    <common-dialog ref="FilePreview" :dialog-data="filePreviewInfo" />
    <common-dialog ref="PdcaReport" :project-id="filterForm.project_id" :options="options" width="60%" height="50%" top="100px" />
    <common-dialog ref="SingleEditBoard" :dialog-data="singleEditInfo" width="60%" height="50%" top="100px" @submit="handleSingleEdit" />
    <div class="filter-box">
      <el-form :model="filterForm" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item prop="name" label="项目名称">
              <el-select v-model="filterForm.project_id" placeholder="项目名称" @change="search">
                <el-option v-for="item in options.filterProjectList" :key="item.id" :label="item.value" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="name" label="类型">
              <el-select v-model="filterForm.type_id" placeholder="类型" @change="search">
                <el-option v-for="item in options.filterTypeList" :key="item.id" :label="item.value" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="name" label="语言">
              <el-select v-model="filterForm.language_id" @change="search">
                <el-option v-for="item in options.filterLanguageList" :key="item.id" :label="item.value" :value="item.id" placeholder="语言" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="editMode" label="状态" placeholder="状态">
              <el-select v-model="filterForm.status" @change="search">
                <el-option v-for="item in options.filterStatusList" :key="item.id" :label="item.value" :value="item.id" placeholder="状态" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item prop="mark" label="是否标记" placeholder="状态">
              <el-select v-model="filterForm.mark" @change="search">
                <el-option v-for="item in options.markList" :key="item.id" :label="item.value" :value="item.id" placeholder="状态" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="name" label="内容">
              <el-input v-model="filterForm.content" @keydown.enter.native="search" placeholder="检索内容" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="name" label="任务时间" placeholder="任务时间">
              <el-date-picker v-model="filterTimeRange" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="完成时间" @change="search" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <button-group :btn-group="filterBtnGroup" position="right" @search-click="search" @reset-filter-click="handleResetFilter" @daily-report-click="handleReport('daily')" @month-report-click="handleReport('month')" />
    </div>
    <div class="content-box">
      <button-group :btn-group="opeBtnGroup" @add-click="add" @del-click="batchDel" />
      <el-table :data="tableData" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :height="tableHeight" @row-dblclick="changeStatus" @selection-change="getSelectList" v-loading="tableLoading">
        <el-table-column align="center" type="selection" width="50" />
        <el-table-column align="center" label="状态" prop="status" width="50">
          <template slot-scope="scope">
            <div :class="scope.row.status == 2 ? 'grey' : 'green'"></div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="项目名称" prop="project_name" width="80">
          <template slot-scope="scope">
            <div v-if="scope.row.editMode == 'edit'">
              <el-select v-model="scope.row.project_name" placeholder="项目名称" @change="changeSelection($event, scope.$index, 'project_id', 'project_name', 'projectList')">
                <el-option v-for="item in options.projectList" :key="item.id" :label="item.value" :value="item.id" />
              </el-select>
            </div>
            <div v-if="scope.row.editMode == 'detail'">
              <el-tag size="small">{{ scope.row.project_name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="类型" prop="type_name" width="80">
          <template slot-scope="scope">
            <div v-if="scope.row.editMode == 'edit'">
              <el-select v-model="scope.row.type_name" placeholder="类型" @change="changeSelection($event, scope.$index, 'type_id', 'type_name', 'typeList')">
                <el-option v-for="item in options.typeList" :key="item.id" :label="item.value" :value="item.id" />
              </el-select>
            </div>
            <div v-if="scope.row.editMode == 'detail'">
              <el-tag type="danger" size="small">{{ scope.row.type_name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="语言" prop="language_name" width="90">
          <template slot-scope="scope">
            <div v-if="scope.row.editMode == 'edit'">
              <el-select v-model="scope.row.language_id" placeholder="语言" @change="changeSelection($event, scope.$index, 'language_id', 'language_name', 'languageList')">
                <el-option v-for="item in options.languageList" :key="item.id" :label="item.value" :value="item.id" />
              </el-select>
            </div>
            <div v-if="scope.row.editMode == 'detail'">
              <el-tag type="warning" size="small">{{ scope.row.language_name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="内容" prop="content" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.row.editMode == 'edit'" class="edit-line">
              <el-input v-model="scope.row.content" />
              <span @click="handleEditDetail(scope.row.content, 'content', scope.row)">
                <img src="@/assets/images/detail.png" alt="">
              </span>
            </div>
            <div v-if="scope.row.editMode == 'detail'">
              {{ scope.row.content }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实施方案" prop="implementation" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.row.editMode == 'edit'" class="edit-line">
              <el-input v-model="scope.row.implementation" />
              <span @click="handleEditDetail(scope.row.implementation, 'implementation', scope.row)">
                <img src="@/assets/images/detail.png" alt="">
              </span>
            </div>
            <div v-if="scope.row.editMode == 'detail'">
              {{ scope.row.implementation }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="创建时间" prop="created_on" /> -->
        <el-table-column align="center" label="备注" prop="remark" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.row.editMode == 'edit'" class="edit-line">
              <el-input v-model="scope.row.remark" />
              <span @click="handleEditDetail(scope.row.remark, 'remark', scope.row)">
                <img src="@/assets/images/detail.png" alt="">
              </span>
            </div>
            <div v-if="scope.row.editMode == 'detail'">
              {{ scope.row.remark }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="开始时间" prop="start_on" width="130">
          <template slot-scope="scope">
            <div v-if="scope.row.editMode == 'edit'">
              <el-date-picker v-model="scope.row.start_on" type="date" placeholder="开始时间" value-format="yyyy-MM-dd" clearable />
            </div>
            <div v-if="scope.row.editMode == 'detail'">
              {{ handleTime(scope.row.start_on) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="完成时间" prop="finish_on" width="130">
          <template slot-scope="scope">
            <div v-if="scope.row.editMode == 'edit'">
              <el-date-picker v-model="scope.row.finish_on" type="date" placeholder="完成时间" value-format="yyyy-MM-dd" clearable />
            </div>
            <div v-if="scope.row.editMode == 'detail'">
              {{ handleTime(scope.row.finish_on) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="附件" prop="fileList" width="50">
          <template slot-scope="scope">
            <!-- <el-button type="text" v-for="file in scope.row.fileList" :key="file.id" @click="handleViewFile(file)">{{ file.filename }}</el-button> -->
            <el-dropdown v-if="scope.row.fileList && scope.row.fileList.length" @command="handleViewFile">
              <span class="el-dropdown-link">
                <i class="el-icon-upload el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="file in scope.row.fileList" :key="file.id" :command="file">{{ file.filename }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="140" fixed="right">
          <template slot-scope="scope">
            <div v-if="scope.row.editMode == 'edit'" style="display: flex; justify-content: center;">
              <el-link type="primary" @click="save(scope.row)">保存</el-link>
              <common-upload text="附件" type="link" @uploadSuccess="handleUploadSuccess($event, scope.row)" />
              <el-link type="danger" @click="cancel(scope.row)">取消</el-link>
            </div>
            <div v-if="scope.row.editMode == 'detail'">
              <el-link type="primary" @click="edit(scope.row)">编辑</el-link>
              <el-link v-if="scope.row.mark == 0" type="primary" @click="handleMark(scope.row, 1)">标记</el-link>
              <el-link v-else type="danger" @click="handleMark(scope.row, 0)">取标</el-link>
              <el-link type="danger" @click="del(scope.row)">删除</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import ButtonGroup from '@/components/Common/ButtonGroup.vue'
import CommonUpload from '@/components/Common/CommonUpload.vue'
import CommonDialog from '@/components/Common/CommonDialog.vue'
export default {
  name: 'Dataset',
  components: {
    ButtonGroup,
    CommonUpload,
    CommonDialog,
  },
  data() {
    return {
      filterForm: {},
      tableData: [
        // {
        //   id: '1',
        //   editMode: 'detail',
        //   project_id: 1,
        //   project_name: 'GRG-FK',
        //   content: '这是内容区域',
        //   type_id: 1,
        //   type_name: '缺陷修复',
        //   language_id: 1,
        //   language_name: 'HTML',
        //   implementation: '先修复，再测试，最后提交代码',
        //   created_on: '2022-01-01',
        //   start_on: '2022-01-01',
        //   finish_on: '2022-01-01',
        //   remark: '备注'
        // }
      ],
      tableLoading: false,
      selectList: [],
      filterBtnGroup: [
        {
          type: 'primary',
          text: '搜索',
          action: 'search'
        },
        {
          type: '',
          text: '重置',
          action: 'reset-filter'
        },
        {
          type: 'primary',
          text: '生成日报',
          action: 'daily-report'
        },
        {
          type: 'primary',
          text: '生成月报',
          action: 'month-report'
        }
      ],
      opeBtnGroup: [
        { type: 'primary', text: '新增', action: 'add' },
        { type: 'danger', text: '删除', action: 'del' }
      ],
      options: {
        filterProjectList: [],
        filterLanguageList: [],
        filterTypeList: [],
        statusList: [{ id: 1, value: '未完成' }, { id: 2, value: '已完成' }],
        filterStatusList: [{ id: null, value: '全部' }, { id: 1, value: '未完成' }, { id: 2, value: '已完成' }],
        markList: [{ id: null, value: '全部' }, { id: 0, value: '未标记' }, { id: 1, value: '已标记' }],
      },
      filterTimeRange: [],
      editRow: {},
      filePreviewInfo: {}, // 附件预览信息
      reportData: [], // 报告信息
      singleEditInfo: {}, // 简单编辑对象
    }
  },
  computed: {
    tableHeight() {
      const pageHeight = document.body.clientHeight
      return pageHeight - 280 < 500 ? 500 : pageHeight - 280
    }
  },
  watch: {
    filterTimeRange(val) {
      if (val) {
        this.filterForm.start_on = val[0]
        this.filterForm.finish_on = val[1]
      } else {
        this.filterForm.start_on = null
        this.filterForm.finish_on = null
      }
    }
  },
  created() {
    this.initOptions()
    this.resetFilter()
    this.search()
  },
  methods: {
    initOptions() {
      this.initProjectList()
      this.initLanguageList()
      this.initTypeList()
    },
    initProjectList() {
      this.$http.dataset.getChildrenById({ id: 14 }).then(res => {
        this.options.projectList = res.data.map(item => ({ id: item.id, value: item.name }))
        this.options.filterProjectList = [{ id: null, value: '全部' }, ...this.options.projectList]
      })
    },
    initLanguageList() {
      this.$http.dataset.getChildrenById({ id: 20 }).then(res => {
        this.options.languageList = res.data.map(item => ({ id: item.id, value: item.name }))
        this.options.filterLanguageList = [{ id: null, value: '全部' }, ...this.options.languageList]
      })
    },
    initTypeList() {
      this.$http.dataset.getChildrenById({ id: 16 }).then(res => {
        this.options.typeList = res.data.map(item => ({ id: item.id, value: item.name }))
        this.options.filterTypeList = [{ id: null, value: '全部' }, ...this.options.typeList]
      })
    },
    resetFilter() {
      const date = new Date()
      const y = date.getFullYear()
      const m = date.getMonth()
      const firstDay = new Date(y, m, 1)
      const lastDay = new Date(y, m + 1, 0)
      this.filterTimeRange = [firstDay, lastDay]
      this.filterForm = {
        status: null,
        project_id: null,
        type_id: null,
        language_id: null,
        mark: null,
        content: '',
        start_on: firstDay,
        finish_on: lastDay
      }
    },
    search() {
      this.tableLoading = true
      const params = {
        ...this.filterForm
      }
      this.$http.pdca.list(params).then(res => {
        this.tableData = res.data.map(item => (item.editMode = 'detail'))
        this.tableData = res.data
        this.tableLoading = false
      })
    },
    handleResetFilter() {
      this.resetFilter()
      this.search()
    },
    add() {
      const obj = {
        editMode: 'edit',
        project_id: this.options.projectList[0].id,
        project_name: this.options.projectList[0].value,
        start_on: new Date()
      }
      const targetProject = this.options.projectList.find(item => item.id == this.filterForm.project_id)
      if (targetProject) {
        obj.project_id = targetProject.id
        obj.project_name = targetProject.value
      }
      this.tableData.unshift(obj)
    },
    del(row) {
      // 接口调用
      this.$http.pdca.delete([row]).then(() => {
        this.$message.success('删除成功')
        this.search()
      })
    },
    // 批量删除
    batchDel() {
      this.$http.pdca.delete(JSON.parse(JSON.stringify(this.selectList))).then(res => {
        this.$message.success('删除成功')
        this.search()
      })
    },
    edit(row) {
      row.editMode = 'edit'
    },
    cancel(row) {
      if (!row.id) {
        this.tableData.shift()
      } else {
        this.search()
      }
    },
    save(row) {
      if (row.id) {
        // 更新
        this.$http.pdca.update([row]).then(res => {
          this.$message.success('保存成功')
          this.search()
        })
      } else {
        // 添加
        this.$http.pdca.add([row]).then(res => {
          this.$message.success('保存成功')
          this.search()
        })
      }
    },
    handleUploadSuccess(info, row) {
      const { id } = row
      const params = {
        id,
        type: 'Pdca',
        fileList: [info]
      }
      this.$http.file.relate(params).then(() => {
        this.$message.success('上传成功')
        this.search()
      })
    },
    // 状态改变
    changeStatus(row) {
      if (row.editMode === 'detail') {
        row.editMode = 'edit'
      }
    },
    // 附件预览
    handleViewFile(file) {
      const { filename } = file
      const ext = filename.split('.')[1]
      if (this.$constant.file.imgExtension.includes(`.${ext}`)) {
        this.filePreviewInfo = file
        this.$refs.FilePreview.handleShow('FilePreview', '附件预览')
      } else if (ext === 'pdf') {
        this.filePreviewInfo = file
        this.$refs.FilePreview.handleShow('FilePreview', '附件预览')
      } else {
        // 非图片类型文件直接下载
        this.$http.common.download(file, filename)
      }
    },
    // 详细编辑
    handleEditDetail(content, key, row) {
      this.singleEditInfo = {
        content, key
      }
      this.editRow = row
      this.$refs.SingleEditBoard.handleShow('SingleEditBoard', '编辑')
    },
    // 简单编辑
    handleSingleEdit({ key, content }) {
      this.editRow[key] = content
      this.save(this.editRow)
    },
    // -------------- 辅助函数
    // 获取selectList
    getSelectList(val) {
      this.selectList = val
    },
    // 通用下拉转换
    changeSelection(val, idx, idPro, namePro, arrName) {
      this.tableData[idx][idPro] = val
      const name = this.options[arrName].find(item => item.id === val).value
      this.tableData[idx][namePro] = name
    },
    handleTime(time) {
      return !time ? null : time.slice(0, 10)
    },
    // 通用报告生成
    handleGenerateReport(params, callback) {
      this.$http.pdca.getReport(params).then(res => {
        callback(res.data)
      })
    },
    handleReport(type) {
      switch (type) {
        case 'daily':
          this.$refs.PdcaReport.handleShow('PdcaReport', '日报', type)
          break
        case 'month':
          this.$refs.PdcaReport.handleShow('PdcaReport', '月报', type)
          break
        default:
          break
      }
    },
    // 标记/取消标记
    handleMark(row, mark) {
      row.mark = mark
      this.$http.pdca.update([row]).then(res => {
        const text = mark ? '标记成功' : '取消标记成功'
        this.$message.success(text)
        this.search()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.card {
  padding: 10px;
}

.filter-box {
  border-bottom: 1px solid #ccc;
  padding-bottom: 10px;
}

.content-box {
  padding-top: 10px;
}
.green, .grey {
  width: 10px;
  height: 10px;
  display: inline-block;
  border-radius: 10px;
}
.green {
  background-color: lightgreen;
}
.grey {
  background-color: lightgray;
}
.edit-line {
  display: flex;
  justify-content: center;
  align-items: center;

  img {
    width: 20px;
    height: 20px;
    position: relative;
    top: 4px;
    &:hover {
      cursor: pointer;
    }
  }
}

// -------------- element相关
::v-deep {
  .el-date-editor .el-icon-date {
    display: none;
  }
  .el-input--prefix .el-input__inner, .el-input__inner {
    padding: 0 10px;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-upload {
    font-size: 20px;
  }
  .el-link {
    margin-right: 6px;
  }

  .el-form-item {
    // margin-right: 0 !important;
  }
  .el-select,
  .el-input_inner {
    width: 100%;
  }
  // 日期控件设置百分百
  .el-date-editor--daterange, .el-date-editor--date {
    width: 100%;
  }
}
</style>
